package com.jacken.mars.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 随机数生成
 *
 * @author wq
 * @date 2020-07-09
 */
public class RandomUtils {

    private static String[] CHARS = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};

    /**
     * 随机获取验证码
     *
     * @param count 位数
     * @return String
     */
    public static String randomCode(int count) {
        Random ran = new Random();
        int bitField = 0;
        char[] chs = new char[count];
        for (int i = 0; i < count; i++) {
            while (true) {
                int k = ran.nextInt(10);
                if ((bitField & (1 << k)) == 0) {
                    bitField |= 1 << k;
                    chs[i] = (char) (k + '0');
                    break;
                }
            }
        }
        return (new String(chs));
    }

    /**
     * 随机生成字符串
     *
     * @param length 长度
     * @return String
     */
    public static String randomString(int length) {
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(26);
            s.append(CHARS[index]);
        }
        return s.toString();
    }

    /**
     * 从集合中随机选取三个元素
     *
     * @param paramList
     * @param count
     * @return
     */
    public  static <T> List<T> getRandomList(List<T> paramList, int count) {
        if (paramList.size() == 0) {
            return paramList;
        }

        Random random = new Random();
        List<Integer> tempList = new ArrayList<>();
        List<T> newList = new ArrayList<>();
        int temp = 0;
        for (int i = 0; i < count; i++) {
            //将产生的随机数作为被抽list的索引
            temp = random.nextInt(paramList.size());
            if (!tempList.contains(temp)) {
                tempList.add(temp);
                newList.add(paramList.get(temp));
            } else {
                i--;
            }
        }
        return newList;
    }
}
